fetch('http://127.0.0.1:5000/movies/top20')
  .then(response => response.json())
  .then(data => {
    console.log('接口返回数据:', data);

    // 排序
    data.sort((a, b) => (b.rater_count || 0) - (a.rater_count || 0));

    const tbody = document.querySelector('#movies-table tbody');
    tbody.innerHTML = ""; // 清空旧内容

    // 创建一个包裹层（scroll-wrapper）放到 tbody 里
    const scrollWrapper = document.createElement('div');
    scrollWrapper.className = 'scroll-wrapper';

    // 添加原始数据行
    data.forEach((movie, index) => {
      const title = movie.title || movie.name || movie.movie_name || '未知';
      const raterCount = movie.rater_count !== undefined ? movie.rater_count.toLocaleString() : '无数据';
      const tr = document.createElement('tr');
      tr.innerHTML = `
        <td>${index + 1}</td>
        <td>${title}</td>
        <td>${raterCount}</td>
      `;
      scrollWrapper.appendChild(tr);
    });

    // 复制前几行（推荐复制前5行）以实现无缝衔接
    for (let i = 0; i < 5 && i < data.length; i++) {
      const title = data[i].title || data[i].name || data[i].movie_name || '未知';
      const raterCount = data[i].rater_count !== undefined ? data[i].rater_count.toLocaleString() : '无数据';
      const tr = document.createElement('tr');
      tr.innerHTML = `
        <td>${i + 1}</td>
        <td>${title}</td>
        <td>${raterCount}</td>
      `;
      scrollWrapper.appendChild(tr);
    }

    // 插入 wrapper
    tbody.appendChild(scrollWrapper);
  })
  .catch(error => {
    const tbody = document.querySelector('#movies-table tbody');
    tbody.innerHTML = `<tr><td colspan="3">无法获取数据，请检查接口是否启动。</td></tr>`;
    console.error('Error fetching data:', error);
  });